#include <iostream>
#include <vector>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
#include <cassert>
#include <cstdlib>
#include <ctime>
#include "Task.hpp"
#define PROCESS_NUM 5
using namespace std;

int waitCommand(int waitFd, bool &quit)
{
    uint32_t command = 0;
    ssize_t s = read(waitFd, &command, sizeof(command));
    if (s == 0)
    {
        quit = true;
        return -1;
    }
    assert(s == sizeof(uint32_t));
    return command;
}
void sendAndWakeup(pid_t who, int fd, uint32_t command)
{
    write(fd, &command, sizeof(command));
    cout << "main process: call precess :[" << who << "] exectue-> " << desc[command] << " through -> " << fd << endl;
}


int main()
{
    load();
    vector<pair<pid_t, int>> slots;
    for (int i = 0; i < PROCESS_NUM; i++)
    {
        int pipefd[2] = {0};
        int n = pipe(pipefd); // 打开管道文件
        // 3 4 3 5 3 6 3 7 3 8 每个子进程都会打开一个
        assert(n != -1);
        (void)n;

        pid_t id = fork();
        assert(id != -1);
        if (id == 0)
        {
            close(pipefd[1]);
            while (true)
            {
                bool quit = false;
                int command = waitCommand(pipefd[0], quit);
                if (quit)
                    break;
                if (command >= 0 && command < handlerSize())
                {
                    callbacks[command]();
                }
                else
                {
                    cout << "非法command" << command << endl;
                }
            }

            exit(1);
        }
        close(pipefd[0]); // 父进程关闭读端
        slots.push_back(make_pair(id, pipefd[1]));
        //cout << " " << pipefd[1] << " ";
    }

    // 父进程派发任务
    srand((unsigned long)time(nullptr) ^ getpid() ^ 1165651);
    while (true)
    {
        // 选择一个任务
        int command = rand() % handlerSize();
        // 选择一个进程，采用随机数的方式，选择进程来完成任务，随机数式的负载均衡
        int choice = rand() % slots.size();
        // 把任务给指定的进程
        sendAndWakeup(slots[choice].first, slots[choice].second, command);
        sleep(1);
    }
    return 0;
}
